<template>
  <view class="sta_wrapper main-top">
    <view class="main-top-bar"/>
    <view class="ul">
        <view class="li" :class="{selected:title === '概览'}" @click="setTextTitle('概览')">
          <text>概览</text>
        </view>
        <view class="li" :class="{selected:title === '支出'}" @click="setTextTitle('支出')">
          <text>支出分析</text>
        </view>
        <view class="li" :class="{selected:title === '收入'}" @click="setTextTitle('收入')">
          <text>收入分析</text>
        </view>
    </view>
    <view class="show-money" v-if="title === '概览'">
      <view class="titleWrapper">
        <Icon iconName="chart"/>
        支出和收入
      </view>
    </view>
    <view v-if="title === '支出'" class="show-money">
      <text class="title">共支出</text>
      <text class="pay">￥{{expensesALL}}</text>
      <text class="count">共{{getCount()}}条支出项目</text>
    </view>
    <view v-if="title === '收入'" class="show-money">
          <text class="title">总收入</text>
          <text class="pay">￥{{incomeAll}}</text>
          <text class="count">共{{getCount(0)}}条收入项目</text>
    </view>
    <canvas canvas-id="myid" id="myid" class="charts" @touchmove="touchMove" @touchstart="scrollStart" @touchend="touchEnd" :ontouch="true" @tap="tap"/>
  </view>
</template>

<script>

import day from 'dayjs'
import { mapState } from 'vuex'
import uCharts from '@/components/u-charts/u-charts.js'

var uChartsInstance = {}

export default {
  computed: {
    ...mapState(['end']),
    dataArray() {
      const { dayTotalList } = this.$store.getters
      const today = new Date(this.end.getTime() - 1)
      const array = []
      const _a = dayTotalList('+')
      const _b = dayTotalList('-')
      for (let i = 0; i <= parseInt(day(today).format('DD')) - 1; i++) {
        const dateString = day(today).subtract(i, 'day').format('MM/DD')
        if ((_a && _a[dateString]) || (_b && _b[dateString])) {
          array.push({
            key: dateString,
            valuesIncome: _a[dateString] ? _a[dateString] : 0,
            valuesExpenses: _b[dateString] ? _b[dateString] : 0
          })
        }
      }
      console.error(array)
      return array
    },
    opt() {
      const { dataArray } = this
      const categories = dataArray.map(item => item.key)
      console.error(categories)
      const valuesIncome = dataArray.map(item => item.valuesIncome)
      const valuesExpenses = dataArray.map(item => item.valuesExpenses)
      const series = [
        { name: '收入', data: valuesIncome, labelShow: false },
        { name: '支出', data: valuesExpenses, labelShow: false }
      ]
      return {
        type: 'line',
        categories,
        series,
        animation: true,
        background: '#FFFFFF',
        color: ['#ffa1a0', '#9bcac0'],
        padding: [15, 10, 0, 15],
        enableScroll: true,
        dataLabel: false,
        xAxis: {
          disableGrid: true,
          itemCount: 8
        },
        yAxis: {
          gridType: 'dash',
          dashLength: 2
        },
        extra: {
          line: {
            type: 'curve',
            width: 3,
            activeType: 'hollow'
          }
        }
      }
    },
    expensesALL() {
      return (this.$store.getters.expenses)
        .map(item => item.amount).reduce((preMoney, amount) => {
          return this.$calc.add(preMoney, amount)
        }, 0)
    },
    incomeAll() {
      return (this.$store.getters.income)
        .map(item => item.amount).reduce((preMoney, amount) => {
          return this.$calc.add(preMoney, amount)
        }, 0)
    },
    exOpt() {
      const { expensesALL } = this
      const { expenses, getSeries } = this.$store.getters
      const series = getSeries(expenses)
      return {
        type: 'pie',
        animation: true,
        background: '#FFFFFF',
        series,
        padding: [5, 5, 5, 5],
        enableScroll: false,
        extra: {
          pie: {
            activeOpacity: 0.5,
            activeRadius: 10,
            offsetAngle: 0,
            labelWidth: 15,
            border: false,
            borderWidth: 3,
            borderColor: '#FFFFFF'
          }
        }
      }
    },
    inOpt() {
      const { income, getSeries } = this.$store.getters
      const series = getSeries(income)
      return {
        type: 'pie',
        animation: true,
        background: '#FFFFFF',
        series,
        color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
        padding: [5, 5, 5, 5],
        enableScroll: false,
        extra: {
          pie: {
            activeOpacity: 0.5,
            activeRadius: 10,
            offsetAngle: 0,
            labelWidth: 15,
            border: false,
            borderWidth: 3,
            borderColor: '#FFFFFF'
          }
        }
      }
    }
  },
  onShow() {
    this.$store.commit('fetchRecords')
  },
  onLoad(e) {
    setTimeout(() => {
      this.drawCharts('myid')
    }, 100)
  },
  data() {
    return {
      title: '概览',
      cWidth: uni.upx2px(750),
      cHeight: uni.upx2px(500)
    }
  },
  methods: {
    getCount(type = 1) {
      const { expenses, income } = this.$store.getters
      return type ? (expenses || []).length : (income || []).length
    },
    setTextTitle(newTitle) {
      this.title = newTitle
      const ext = newTitle === '概览' ? this.opt : (newTitle === '支出' ? this.exOpt : this.inOpt)
      this.drawCharts('myid', ext)
    },
    scrollStart(e) {
      uChartsInstance[e.target.id].scrollStart(e)
    },
    touchMove(e) {
      uChartsInstance[e.target.id].scroll(e)
    },
    touchEnd(e) {
      uChartsInstance[e.target.id].scrollEnd(e)
    },
    drawCharts(id, opts = this.opt) {
      const ctx = uni.createCanvasContext(id, this)
      ctx.clearRect(0, 0, this.cWidth, this.cHeight)
      const opt = Object.assign({
        width: this.cWidth,
        height: this.cHeight,
        context: ctx
      }, opts)
      uChartsInstance[id] = new uCharts(opt)
    },
    tap(e) {
      uChartsInstance[e.target.id].touchLegend(e)
      uChartsInstance[e.target.id].showToolTip(e)
    }

  }
}

</script>

<style lang="scss" scoped>
  .show-money {
    margin-top: 48rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    view {
      padding: 5px;
      font-weight: 700;
    }

    .title {
      color: #81B7AA;
    }

    .titleWrapper {
      display: flex;
      flex-direction: row;
      align-items: center;
      border-bottom: 5px solid $uni-color-primary;
      font-size: 26px;
      padding: 8px;
      color: rgba(185, 186, 184, 0.9);

      & .icon {
        margin-right: 12px;
        width: 38px;
        height: 38px;
        fill: $uni-color-primary;
      }
    }

    .pay {
      font-size: 28px;
      color: #81B7AA;
    }

    .count {
      margin-top: 10px;
      font-size: 18px;
      color: rgba(185, 186, 184, 0.9);
      padding: 10px 16px;
      background-color: #f9faf5;
      border-radius: 8px;
    }

    .income {
      margin-top: 15px;
      color: #B7B7B7;
      font-size: 16px;
    }
  }
  .sta_wrapper {
    .ul {
      padding-top: calc(var(--status-bar-height) + 30rpx);
      display: flex;
        font-size: 32rpx;
      justify-content: center;

      .li {
        margin: 4px 8px;
        padding: 0 24px;
        line-height: 66rpx;
        height: 66rpx;
        background-color: #fff;
        color: #333;
        border-radius: 8rpx;

        &.selected {
          background-color: $uni-color-btn;
          color: #fff;
        }
      }
    }
  }
  .charts{
    margin-top: 20rpx;
    width: 100%;
    height: 500rpx;
  }
</style>
